package com.wo.cloud.mybatis.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.wo.cloud.mybatis.props.MybatisPlusConfigProperties;
import com.wo.cloud.tenant.handler.WoCloudTenantHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/11 16:40
 * Description: mybatis plus 多租户配置
 */
@Configuration
//@MapperScan("com.baomidou.mybatisplus.samples.tenant.mapper")
public class MybatisPlusConfig {

    @Autowired
    private MybatisPlusConfigProperties plusProperties;


    // 获取woCloudTenantHandler bean实例
    @Qualifier(value = "woCloudTenantHandler")
    @Autowired
    private WoCloudTenantHandler woCloudTenantHandler;

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(WoCloudTenantHandler woCloudTenantHandler) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 注意 ”分页和租户“ 顺序
        if (plusProperties.getEnableTenant()) {
            System.out.println("enable tenant:" + plusProperties.getEnableTenant());
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(woCloudTenantHandler));
        }
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false (如下： configurationCustomizer())
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}
